package com.zllkj.mm.api;

import com.zllkj.mm.api.network.SessionInterceptor;
import com.zllkj.mm.api.network.converter.JsonConverterFactory;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelperV2 {

    private static OkHttpClient configClient(final boolean haveToken) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        File cacheFile = new File(MDConstant.PATH_CACHE);
//        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        // 设置Token
        if (haveToken) {
            builder.addInterceptor(new SessionInterceptor());
        }
        // 设置超时
        builder.connectTimeout(100, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        // 错误重连
        builder.retryOnConnectionFailure(true);

        return builder.build();
    }



    public static <T> T configRetrofit(Class<T> service, String url, boolean haveToken) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(configClient(haveToken))
                .addConverterFactory(JsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(service);
    }


    public static <T> T createOauthService(Class<T> service, String url, boolean haveToken) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(configClient(haveToken))
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(service);
    }

}
